package com.ruoyi.detail.contreoller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.common.utils.poi.WordExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;

/**
 * @author : tianyu
 * @date : 2025-01-16 11:18
 * @Version: 1.0
 * @Desc : 用于以word格式导出会话详情
 */
@RestController
@RequestMapping("/export")
public class SessionDetailExportController {
    @Autowired
    private WordExportService wordExportService;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/word")
    public ResponseEntity<byte[]> downloadWord(@RequestParam("sessionDetailId") String sessionDetailId) throws IOException {
        String redisKey = "session_detail_" + sessionDetailId;
        Object o = redisUtil.get(redisKey);
        // 判断是否为 JSON 字符串，进行反序列化
        byte[] wordFile = null;
        if (o instanceof String) {
            String jsonString = (String) o;

            // 使用 ObjectMapper 来解析 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();

            try {
                // 将 JSON 字符串反序列化为 HashMap
                HashMap<String, String> sessionDetailMap = objectMapper.readValue(jsonString, HashMap.class);

                // 生成 Word 文件
                wordFile= wordExportService.generatePaper(sessionDetailMap);

                // 其他操作
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (o instanceof HashMap) {
            // 如果 Redis 中已经是 HashMap 类型
            HashMap<String, String> sessionDetailMap = (HashMap<String, String>) o;

            // 生成 Word 文件
           wordFile = wordExportService.generatePaper(sessionDetailMap);

            // 其他操作
        }

        // 设置响应头，指示浏览器下载文件
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=paper.docx");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(wordFile);
    }
}
